import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Select,
  DatePicker,
  message,
  Tag,
  Typography,
  Row,
  Col,
  Statistic,
  Descriptions,
  List,
  InputNumber,
  Divider
} from 'antd';
import {
  EyeOutlined,
  SearchOutlined,
  ReloadOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { orderAPI, userAPI, productAPI } from '../../services/api';

const { Title } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

const OrderManagement = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [orderItems, setOrderItems] = useState([]);
  const [statusFilter, setStatusFilter] = useState('');
  const [dateRange, setDateRange] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [stats, setStats] = useState({
    totalOrders: 0,
    totalRevenue: 0,
    pendingOrders: 0,
    completedOrders: 0
  });

  // 订单状态选项
  const statusOptions = [
    { label: '待支付', value: 'PENDING', color: 'orange' },
    { label: '已支付', value: 'PAID', color: 'blue' },
    { label: '已发货', value: 'SHIPPED', color: 'cyan' },
    { label: '已完成', value: 'DELIVERED', color: 'green' },
    { label: '已取消', value: 'CANCELLED', color: 'red' }
  ];

  // 加载订单列表
  const loadOrders = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      let response;
      
      // 根据筛选条件加载订单
      if (dateRange.length === 2) {
        const startDate = dateRange[0].format('YYYY-MM-DD');
        const endDate = dateRange[1].format('YYYY-MM-DD');
        response = await orderAPI.getByDateRange(startDate, endDate);
      } else {
        response = await orderAPI.getAll(page - 1, pageSize);
      }
      
      if (response?.content) {
        let filteredOrders = response.content;
        
        // 状态筛选
        if (statusFilter) {
          filteredOrders = filteredOrders.filter(order => order.status === statusFilter);
        }
        
        setOrders(filteredOrders);
        setPagination(prev => ({
          ...prev,
          current: page,
          total: response.totalElements
        }));
      } else if (Array.isArray(response)) {
        let filteredOrders = response;
        
        // 状态筛选
        if (statusFilter) {
          filteredOrders = filteredOrders.filter(order => order.status === statusFilter);
        }
        
        setOrders(filteredOrders);
        setPagination(prev => ({
          ...prev,
          current: page,
          total: filteredOrders.length
        }));
      }
    } catch (error) {
      console.error('加载订单列表失败:', error);
      message.error('加载订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载统计数据
  const loadStats = async () => {
    try {
      const response = await orderAPI.getStats();
      setStats({
        totalOrders: response?.totalOrders || 0,
        totalRevenue: response?.totalRevenue || 0,
        pendingOrders: response?.pendingOrders || 0,
        completedOrders: response?.completedOrders || 0
      });
    } catch (error) {
      console.error('加载统计数据失败:', error);
      // 使用模拟数据
      setStats({
        totalOrders: orders.length,
        totalRevenue: orders.reduce((sum, order) => sum + (order.totalAmount || 0), 0),
        pendingOrders: orders.filter(order => order.status === 'PENDING').length,
        completedOrders: orders.filter(order => order.status === 'DELIVERED').length
      });
    }
  };

  // 分页变化
  const handleTableChange = (paginationConfig) => {
    setPagination(paginationConfig);
    loadOrders(paginationConfig.current, paginationConfig.pageSize);
  };

  // 查看订单详情
  const handleViewOrder = async (order) => {
    setSelectedOrder(order);
    setDetailModalVisible(true);
    
    try {
      // 模拟订单项数据（实际项目中应该有专门的API）
      const mockOrderItems = [
        {
          id: 1,
          productId: 1,
          productName: '示例商品1',
          price: 99.99,
          quantity: 2,
          subtotal: 199.98
        },
        {
          id: 2,
          productId: 2,
          productName: '示例商品2',
          price: 149.99,
          quantity: 1,
          subtotal: 149.99
        }
      ];
      setOrderItems(mockOrderItems);
    } catch (error) {
      console.error('加载订单详情失败:', error);
      message.error('加载订单详情失败');
    }
  };

  // 更新订单状态
  const handleUpdateStatus = async (orderId, newStatus) => {
    try {
      await orderAPI.updateStatus(orderId, newStatus);
      message.success('订单状态更新成功');
      loadOrders(pagination.current, pagination.pageSize);
      loadStats();
      
      // 如果详情模态框打开，更新选中的订单状态
      if (selectedOrder && selectedOrder.id === orderId) {
        setSelectedOrder(prev => ({ ...prev, status: newStatus }));
      }
    } catch (error) {
      console.error('更新订单状态失败:', error);
      message.error('更新订单状态失败');
    }
  };

  // 支付订单
  const handlePayOrder = async (orderId) => {
    try {
      await orderAPI.pay(orderId);
      message.success('订单支付成功');
      loadOrders(pagination.current, pagination.pageSize);
      loadStats();
    } catch (error) {
      console.error('订单支付失败:', error);
      message.error('订单支付失败');
    }
  };

  // 取消订单
  const handleCancelOrder = async (orderId) => {
    try {
      await orderAPI.cancel(orderId);
      message.success('订单取消成功');
      loadOrders(pagination.current, pagination.pageSize);
      loadStats();
    } catch (error) {
      console.error('订单取消失败:', error);
      message.error('订单取消失败');
    }
  };

  // 状态筛选变化
  const handleStatusFilterChange = (value) => {
    setStatusFilter(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 日期范围变化
  const handleDateRangeChange = (dates) => {
    setDateRange(dates || []);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 刷新数据
  const handleRefresh = () => {
    loadOrders(pagination.current, pagination.pageSize);
    loadStats();
  };

  // 初始加载
  useEffect(() => {
    loadOrders();
  }, []);

  // 当筛选条件变化时重新加载
  useEffect(() => {
    if (pagination.current === 1) {
      loadOrders(1, pagination.pageSize);
    } else {
      setPagination(prev => ({ ...prev, current: 1 }));
    }
  }, [statusFilter, dateRange]);

  // 当订单列表变化时更新统计
  useEffect(() => {
    loadStats();
  }, [orders]);

  // 获取状态配置
  const getStatusConfig = (status) => {
    return statusOptions.find(option => option.value === status) || statusOptions[0];
  };

  // 获取可用的状态转换选项
  const getAvailableStatusTransitions = (currentStatus) => {
    const transitions = {
      'PENDING': ['PAID', 'CANCELLED'],
      'PAID': ['SHIPPED', 'CANCELLED'],
      'SHIPPED': ['DELIVERED'],
      'DELIVERED': [],
      'CANCELLED': []
    };
    
    return transitions[currentStatus] || [];
  };

  // 表格列定义
  const columns = [
    {
      title: '订单ID',
      dataIndex: 'id',
      key: 'id',
      width: 100
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 100
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount) => `¥${parseFloat(amount || 0).toFixed(2)}`,
      sorter: (a, b) => (a.totalAmount || 0) - (b.totalAmount || 0)
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color}>{config.label}</Tag>;
      },
      filters: statusOptions.map(option => ({
        text: option.label,
        value: option.value
      })),
      onFilter: (value, record) => record.status === value
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-',
      sorter: (a, b) => dayjs(a.createdAt).unix() - dayjs(b.createdAt).unix()
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 150,
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => {
        const availableTransitions = getAvailableStatusTransitions(record.status);
        
        return (
          <Space size="small" direction="vertical">
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={() => handleViewOrder(record)}
              size="small"
            >
              查看详情
            </Button>
            
            {availableTransitions.length > 0 && (
              <Select
                placeholder="更新状态"
                size="small"
                style={{ width: 100 }}
                onChange={(value) => handleUpdateStatus(record.id, value)}
              >
                {availableTransitions.map(status => {
                  const config = getStatusConfig(status);
                  return (
                    <Option key={status} value={status}>
                      {config.label}
                    </Option>
                  );
                })}
              </Select>
            )}
            
            {record.status === 'PENDING' && (
              <Button
                type="link"
                size="small"
                onClick={() => handlePayOrder(record.id)}
              >
                支付
              </Button>
            )}
            
            {['PENDING', 'PAID'].includes(record.status) && (
              <Button
                type="link"
                danger
                size="small"
                onClick={() => handleCancelOrder(record.id)}
              >
                取消
              </Button>
            )}
          </Space>
        );
      }
    }
  ];

  return (
    <div className="order-management">
      {/* 页面头部 */}
      <div className="page-header">
        <Title level={2}>订单管理</Title>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="订单总数"
              value={stats.totalOrders}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总收入"
              value={stats.totalRevenue}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="元"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="待处理订单"
              value={stats.pendingOrders}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="已完成订单"
              value={stats.completedOrders}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 筛选工具栏 */}
      <Card className="toolbar-card">
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Select
                placeholder="筛选状态"
                allowClear
                style={{ width: 150 }}
                value={statusFilter}
                onChange={handleStatusFilterChange}
              >
                {statusOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
              
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                format="YYYY-MM-DD"
                value={dateRange}
                onChange={handleDateRangeChange}
              />
            </Space>
          </Col>
          <Col>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 订单表格 */}
      <Card className="table-card">
        <Table
          columns={columns}
          dataSource={orders}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        title="订单详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        {selectedOrder && (
          <div>
            {/* 订单基本信息 */}
            <Descriptions title="订单信息" bordered column={2}>
              <Descriptions.Item label="订单ID">{selectedOrder.id}</Descriptions.Item>
              <Descriptions.Item label="用户ID">{selectedOrder.userId}</Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusConfig(selectedOrder.status).color}>
                  {getStatusConfig(selectedOrder.status).label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">
                ¥{parseFloat(selectedOrder.totalAmount || 0).toFixed(2)}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {selectedOrder.createdAt ? dayjs(selectedOrder.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {selectedOrder.updatedAt ? dayjs(selectedOrder.updatedAt).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="备注" span={2}>
                {selectedOrder.remark || '无'}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            {/* 订单项列表 */}
            <div>
              <Title level={4}>订单商品</Title>
              <List
                dataSource={orderItems}
                renderItem={(item) => (
                  <List.Item>
                    <List.Item.Meta
                      title={item.productName}
                      description={`商品ID: ${item.productId}`}
                    />
                    <div>
                      <Space direction="vertical" align="end">
                        <span>单价: ¥{parseFloat(item.price || 0).toFixed(2)}</span>
                        <span>数量: {item.quantity}</span>
                        <span style={{ fontWeight: 'bold' }}>
                          小计: ¥{parseFloat(item.subtotal || 0).toFixed(2)}
                        </span>
                      </Space>
                    </div>
                  </List.Item>
                )}
              />
            </div>

            <Divider />

            {/* 状态操作 */}
            <div>
              <Title level={4}>订单操作</Title>
              <Space>
                {getAvailableStatusTransitions(selectedOrder.status).map(status => {
                  const config = getStatusConfig(status);
                  return (
                    <Button
                      key={status}
                      type="primary"
                      onClick={() => handleUpdateStatus(selectedOrder.id, status)}
                    >
                      更新为{config.label}
                    </Button>
                  );
                })}
                
                {selectedOrder.status === 'PENDING' && (
                  <Button
                    type="primary"
                    onClick={() => handlePayOrder(selectedOrder.id)}
                  >
                    支付订单
                  </Button>
                )}
                
                {['PENDING', 'PAID'].includes(selectedOrder.status) && (
                  <Button
                    danger
                    onClick={() => handleCancelOrder(selectedOrder.id)}
                  >
                    取消订单
                  </Button>
                )}
              </Space>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrderManagement;